package com.universest.swordholder.tools

import android.database.Cursor
import android.net.Uri
import android.provider.OpenableColumns
import android.util.Log
import com.universest.swordholder.SwordHolderApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.InputStream

class UriFile(val uri: Uri) {


    private val context
        get() = SwordHolderApplication.instance

    suspend fun queryFileName(): String {
        return queryFor(OpenableColumns.DISPLAY_NAME, "") {
            getString(it)
        }
    }

    suspend fun queryFileSize(): Long {
        return queryFor(OpenableColumns.SIZE, 0L) {
            getLong(it)
        }
    }

    suspend fun queryFileNameAndSize(): Pair<String, Long> {
        return withContext(Dispatchers.IO) {
            try {
                val cursor = context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME,
                    OpenableColumns.SIZE), null, null, null)
                val result = cursor?.use {
                    if (it.moveToFirst()) {
                        val nameColumnIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                        val sizeColumnIndex = it.getColumnIndex(OpenableColumns.SIZE)
                        return@use Pair(it.getString(nameColumnIndex)?:"", it.getLong(sizeColumnIndex))
                    }
                    return@use null
                }
                return@withContext result ?: Pair("", 0L)
            } catch (e: Exception) {
                Log.e("UriFile", e.message ?: "")
            }
            return@withContext Pair("", 0L)
        }
    }

    suspend fun openFile(): InputStream?{
        return withContext(Dispatchers.IO) {
            try {
                val inputStream = context.contentResolver.openInputStream(uri)
                return@withContext inputStream
            } catch (e: Exception) {
                Log.e("UriFile", e.message ?: "")
                return@withContext null
            }
        }
    }

    private suspend fun <T> queryFor(column: String, default:T, block:Cursor.(columnIndex:Int) -> T): T {
        return withContext(Dispatchers.IO) {
            try {
                val cursor = context.contentResolver.query(uri, arrayOf(column), null, null, null)
                cursor?.use {
                    if (it.moveToFirst()) {
                        val index = it.getColumnIndex(column)
                        return@use cursor.block(index)
                    }
                }
            } catch (e: Exception) {
                Log.e("UriFile", e.message ?: "")
            }
            return@withContext default
        }
    }
}